/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null || n == 0) {
            return head;
        }
        int l = length(head);
        if(n == l) {
            head = head.next;
            return head;
        }
        ListNode cur = head;
        for(int i = 1;i < (l - n);i++) {
            cur = cur.next;
        }
        cur.next = cur.next.next;
        return head;
    }

    private int length(ListNode head) {
        int l = 0;
        while(head != null) {
            l++;
            head = head.next;
        }
        return l;
    }
}